#include <iomanip> // std::put_time
#include <iostream>
#include <sys/epoll.h>

#include "../code/TimerQueue.h"

std::string getCurTime()
{
    auto now = std::chrono::system_clock::now();
    std::time_t now1 = std::chrono::system_clock::to_time_t(now);
    std::tm now2 = *std::localtime(&now1);

    std::ostringstream oss;
    oss << std::put_time(&now2, "%Y-%m-%d %H:%M:%S");
    return oss.str();
}

int main()
{
    // 添加定时器————————————————————
    Timer::TimerQueue timerQueue{};
    auto now = std::chrono::system_clock::now();
    // 第一个定时器：第0s触发，重复每2s触发
    timerQueue.addTimer(now + std::chrono::seconds(2), std::chrono::seconds(2), []()
                        { std::cout << "[" << getCurTime() << "] 2秒定时器触发" << std::endl; });
    // 第二个定时器：第5s触发，不重复
    timerQueue.addTimer(now + std::chrono::seconds(5), std::chrono::seconds(0), []()
                        { std::cout << "[" << getCurTime() << "] 5秒定时器触发" << std::endl; });

    std::cout << "[" << getCurTime() << "] 等待定时器触发..." << std::endl;

    // 处理定时器————————————————————
    int epollFd = epoll_create1(0);
    if (epollFd == -1)
    {
        std::cerr << "Failed to epoll_create1()" << std::endl;
        return 1;
    }

    struct epoll_event ev{};
    ev.events = EPOLLIN;
    int timerFd = timerQueue.getTimerFd();
    ev.data.fd = timerFd;
    if (epoll_ctl(epollFd, EPOLL_CTL_ADD, timerFd, &ev) == -1)
    {
        std::cerr << "Failed to epoll_ctl()" << std::endl;
        return 1;
    }

    auto beginTime = std::chrono::system_clock::now();
    const int maxRevents = 10;
    struct epoll_event rev[maxRevents];
    while (true)
    {
        auto endTime = std::chrono::system_clock::now();
        auto elapsedTime = std::chrono::duration_cast<std::chrono::seconds>(endTime - beginTime).count();
        if (elapsedTime >= 10)
        {
            std::cout << "[" << getCurTime() << "] 已运行约10秒, 退出" << std::endl;
            break;
        }

        int n = epoll_wait(epollFd, rev, maxRevents, 0);
        if (n > 0)
        {
            for (int i = 0; i < n; ++i)
            {
                if (rev[i].data.fd == timerFd)
                {
                    timerQueue.handleTimers(); // 处理
                }
            }
        }
    }

    return 0;
}